<template>
  <div class="page">

    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="组织名称：">
          <el-input v-model="formInline.orgName" placeholder="组织名称"></el-input>
        </el-form-item>
        <el-form-item label="组织状态：">
          <el-select v-model="formInline.enableStatus" placeholder="组织状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="1"></el-option>
            <el-option label="不显示" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="onSearch">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openDialog()">新增组织</el-button>
      </div>
      <!-- 操作区域 end -->
      <el-table class="el_table" size="small" :data="tableData" row-key="id" stripe lazy :load="getNodes" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="departmentName" label="组织名称" />
        <!-- <el-table-column prop="orderNum" label="排序" />
        <el-table-column prop="enableStatus" label="状态">
          <template slot-scope="scope">
            <span :class="scope.row.enableStatus == 2?'stop_status':'normal_status'">{{scope.row.enableStatus == 1?'正常':'停用'}}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="createdDate" label="创建时间" />
        <el-table-column prop="createdDate" label="操作" width="120">
          <template slot-scope="scope">
            <!-- <el-link type="primary" class="el_link" :underline="underline" @click="openDialog('',scope.row)">新增</el-link> -->
            <el-link type="primary" class="el_link" :underline="underline" @click="openDialog(scope.row.id)">编辑</el-link>
            <el-link type="danger" class="el_link" :underline="underline" @click="remove(scope.row.id)">删除</el-link>
            <!-- <el-button type="primary" plain size="mini" :id="scope.row.id" @click="openDialog('',scope.row)">新增</el-button>
            <el-button type="success" plain size="mini" @click="openDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" plain size="mini" @click="remove(scope.row.id)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize" :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList" @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->

    <!-- 弹框 开始 -->
    <public-dialog :show="showDialog" :title="currentId?'编辑组织':'新增组织'" @close="closeDialog">
      <div>
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="120px" size="medium">
          <el-form-item label="上级部门：" prop="superiorName">
            <!-- <el-cascader class="a_input" :disabled="currentId?true:false" :options="optionsTree" v-model="addForm.superiorId" :props="{ checkStrictly: true,value:'id', label:'label',expandTrigger:'click',emitPath:false }" clearable></el-cascader> -->
            <el-popover v-model="showPopover" placement="bottom" width="400" trigger="click">
              <div class="tree_box">
                <el-tree :data="optionsTree" highlight-current :current-node-key="currentNodeKey" @node-click="nodeClick"></el-tree>
              </div>
              <el-input slot="reference" v-model="addForm.superiorName" class="a_input" :suffix-icon="showPopover?'el-icon-arrow-up':'el-icon-arrow-down'" readonly placeholder="上级部门"></el-input>
            </el-popover>
          </el-form-item>
          <el-form-item label="部门名称：" prop="departmentName">
            <el-input v-model="addForm.departmentName" class="a_input"></el-input>
          </el-form-item>
          <el-form-item label="显示排序：" prop="orderNum">
            <el-input-number v-model="addForm.orderNum" :controls="false" class="a_input"></el-input-number>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" plain size="small" @click="saveInfo">确定</el-button>
        <el-button type="default" plain size="small" @click="closeDialog">取消</el-button>
      </div>
    </public-dialog>
    <!-- 弹框 end -->

  </div>
</template>

<script>
import {
  ORGANIZATIONSEARCH,
  GETORGANIZATIONCHILDREN,
  GETORGANIZATIONTREE,
  ADDORGANIZATION,
  GETORGANIZATIONINFO,
  EDITORGANIZATION,
  DELETEORGANIZATION,
} from "@/http/system";
import { showModal, showToast, deepClone } from "@/common/util";
import PublicDialog from "@/components/Dialog";
export default {
  components: {
    PublicDialog,
  },
  data() {
    return {
      underline: false,
      formInline: {},
      tableData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 30, 40],
      pageSize: 10,
      loading: false,
      addForm: {},
      showDialog: false,
      currentId: "",
      addFormRules: {
        superiorName: [
          { required: true, message: "请选择上级部门", trigger: "change" },
        ],
        departmentName: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "请输入显示排序", trigger: "blur" },
        ],
        enableStatus: [
          { required: true, message: "请选择组织状态", trigger: "blur" },
        ],
      },
      parentNodes: {},
      optionsTree: [],
      showPopover: false,
      currentNodeKey: "",
    };
  },
  mounted() {
    this.getList();
    this.getOrganization();
  },
  methods: {
    /** 获取列表 */
    getList() {
      let _this = this;
      let oParams = _this.getParams();
      oParams.pageNumber = _this.pageNumber;
      _this.loading = true;
      ORGANIZATIONSEARCH(oParams).then((res) => {
        _this.loading = false;
        let obj = res.data || {};
        _this.tableData = obj.list || [];
        _this.pageTotal = obj.totalElements;
      });
    },
    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e;
      this.getList();
    },

    /** 获取参数 */
    getParams() {
      let o = JSON.parse(JSON.stringify(this.formInline));
      o.pageSize = this.pageSize;
      return o;
    },

    /** 获取子节点 */
    getNodes(tree, treeNode, resolve) {
      GETORGANIZATIONCHILDREN({ rootId: tree.id }).then((res) => {
        let nodes = res.data;
        resolve(nodes);
      });
    },

    /** 打开弹框 */
    openDialog(id, item) {
      this.showDialog = true;
      this.currentId = id;

      this.parentNodes = item;
      if (id) {
        this.getInfo(id);
      }
    },

    /** 关闭弹框 */
    closeDialog() {
      this.currentId = "";
      this.showDialog = false;
      this.addForm = {};
      this.parentNodes = {};
      this.$refs.addForm.clearValidate();
    },

    /** 保存数据 */
    saveInfo() {
      let _this = this;
      _this.loading = true;
      _this.$refs.addForm.validate((valid) => {
        console.log(valid);
        if (!valid) {
          _this.loading = false;
          return false;
        }
        let oParams = deepClone(_this.addForm);
        delete oParams.superiorName;
        console.log(oParams);
        // 编辑
        if (oParams.id) {
          EDITORGANIZATION(oParams).then((res) => {
            _this.loading = false;
            if (res.code == 200) {
              showToast({
                message: "编辑成功",
                type: "success",
              });
              _this.closeDialog();
              _this.getList();
            }
          });
          return false;
        }

        //新增
        ADDORGANIZATION(oParams).then((res) => {
          _this.loading = false;
          if (res.code == 200) {
            showToast({
              message: "添加成功",
              type: "success",
            });
            _this.closeDialog();
            _this.getList();
          }
        });
      });
    },

    /** 获取组织信息 */
    getInfo(id) {
      let _this = this;
      GETORGANIZATIONINFO({ id: id }).then((res) => {
        console.log(res);
        let obj = res.data || {};
        let o = {};
        o.id = obj.id;
        o.departmentName = obj.departmentName;
        o.orderNum = obj.orderNum;
        o.superiorName = obj.superiorName;
        o.superiorId = obj.superiorId;
        _this.addForm = o;
        _this.currentNodeKey = obj.superiorId;
      });
    },

    /** 删除组织机构 */
    remove(id) {
      let _this = this;
      if (!id) {
        return false;
      }
      showModal({
        message: "确认删除该组织机构吗？",
        type: "warning",
        showCancelButton: true,
        success: () => {
          DELETEORGANIZATION({ id: id }).then((res) => {
            if (res.code == 200) {
              _this.getList();
              showToast({
                message: "删除成功",
                type: "success",
              });
            }
          });
        },
      });
    },

    // 重置
    rest() {
      this.formInline = {};
      this.getList();
    },

    // 获取一级组织机构
    getOrganization() {
      GETORGANIZATIONTREE().then((res) => {
        let list = res.data || [];
        this.optionsTree = [list[0]||{}];
      });
    },

    // 监听树节点点击
    nodeClick(data) {
      this.addForm.superiorId = data.id;
      this.addForm.superiorName = data.label;
      this.showPopover = false;
      this.$refs.addForm.clearValidate("superiorName");
    },

    // 搜索
    onSearch(){
      this.pageNumber = 1;
      this.getList()
    }
  },
};
</script>

<style lang="scss">
.a_input {
  input {
    text-align: left !important;
  }
}
</style>
<style lang="scss" scoped>
.stop_status,
.normal_status {
  position: relative;
  padding-left: 10px;
  color: #f00;
}
.normal_status {
  color: #31b311;
}
.stop_status:after,
.normal_status:after {
  display: block;
  content: "";
  width: 8px;
  height: 8px;
  border-radius: 100%;
  background: #f00;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translate(0, -50%);
}
.normal_status:after {
  background: #31b311;
}
.a_input {
  width: 280px;
}
.tree_box{
  max-height: 300px;
  overflow-y: auto;
}
</style>
